# partially based on django-tremenus code written by Julien Phalip
# (http://code.google.com/p/django-treemenus/)
#
# Copyright (c) 2008, Julien Phalip
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
#     * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
#     * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

from django import template
from djwheel.app.contenttree.models import Menu, MenuItem, FreeContent, Legend
from djwheel.app.contenttree.core import get_content, get_menu_item
from djwheel.utils import trunc_text
from djwheel.utils import assert_has_request

register = template.Library()

@register.inclusion_tag('contenttree/menu_branch.html', takes_context=True)
def show_menu(context, menu_name="main", menu_type=None):
    menu = Menu.objects.get(name=menu_name)
    context['menu_item'] = menu.root_item
    context['menu_type'] = menu_type
    return context

@register.inclusion_tag('contenttree/top_menu.html', takes_context=True)
def show_top_menu(context, menu_name="main"):
    assert_has_request(context)
    request = context['request']

    menu = Menu.objects.get(name=menu_name)
    context['items'] = [(menu_item, _menu_item(menu_item, context, request)) for menu_item in menu.root_item.children()]
    return context

@register.inclusion_tag('contenttree/section_menu.html', takes_context=True)
def show_section_menu(context, menu_name="main"):
    assert_has_request(context)
    request = context['request']

    active_menu_item = get_page_or_parent(request.path)
    m = active_menu_item
    #print '---'
    while m and m.level > 1:
        #print 'level', m.level, m.get_url()
        m = m.parent
    context['menu_item'] = m
#    active_menu_item =
#    current = None
#    for child in menu.root_item.children():
#        #if child.get_url() == request.path:
#        print request.path, child.get_url(), child.get_self_or_child_url()
#        if child.get_self_or_child_url() == request.path:
#
#            break
#    if current:
#        pass
#    print '---'
    return context

@register.inclusion_tag('contenttree/menu_branch.html', takes_context=True)
def show_menu_branch(context, menu_item):
    context['menu_item'] = menu_item
    return context

def _menu_item(menu_item, context, request):
    if menu_item.is_splitter():
        return {
            'menu_item': menu_item,
        }

    link = menu_item.get_self_or_child_url()
    if menu_item == context.get('ACTIVE_TRANSIT_MENU_ITEM'):
        return {
            'menu_item': menu_item,
            'link': link,
            'is_active': False,
            'is_active_transit': True,
        }
    active_menu_item = get_page_or_parent(request.path)

    is_active_transit = False
    #is_active = False
    is_active = active_menu_item == menu_item

    m = active_menu_item
    while m and m.parent:
        if m == menu_item:
            is_active_transit = True
            break
        m = m.parent

    if is_active:
        #print menu_item.get_url(), request.path
        if menu_item.get_url() != request.path:
            is_active = False
            is_active_transit = True

#    print '$', is_active, is_active_transit, link

    return {
        'menu_item': menu_item,
        'link': link,
        'is_active': is_active,
        'is_active_transit': is_active_transit,
    }

@register.inclusion_tag('contenttree/menu_item.html', takes_context=True)
def show_menu_item(context, menu_item):
    if not isinstance(menu_item, MenuItem):
        raise template.TemplateSyntaxError, 'Given argument must be a MenuItem object.'

    assert_has_request(context)
    request = context['request']

    context.update(_menu_item(menu_item, context, request))
    return context

def get_page_or_parent(path, menu_names=()):
    return get_menu_item(path, menu_names) or get_menu_item(path.rsplit('/', 2)[0] + '/', menu_names)

def breadcrumbs_items(path, menu_names=()):
    items = []
    item = get_page_or_parent(path, menu_names)
    if item:
        while item.parent:
            items.insert(0, item)
            item = item.parent
    return items

@register.inclusion_tag('contenttree/breadcrumbs.html', takes_context=True)
def show_breadcrumbs(context, last_elem=None, trunc_last_elem=30):
    assert_has_request(context)
    request = context['request']

    if last_elem:
        last_elem = trunc_text(last_elem, trunc_last_elem, by_spaces=True)
    return {
        'items': breadcrumbs_items(request.path),
        'last_elem': last_elem,
        'request': request,
    }

@register.simple_tag
def show_freecontent(name):
    try:
        return FreeContent.objects.get(name=name).value
    except FreeContent.DoesNotExist:
        return ''

@register.simple_tag
def show_legend(name):
    try:
        return Legend.objects.get(name=name).value
    except Legend.DoesNotExist:
        return ''
